package validator

import (
	"encoding/json"
	"errors"
	"fmt"
	apis2 "gluenet/pkg/apis"
	"gluenet/pkg/meta"
	"gluenet/pkg/ops/dbi"
	"regexp"
)

type validator struct {
	DB dbi.GlueDB
}

func NewValidator(db dbi.GlueDB) apis2.GlueValidator {
	return validator{DB: db}
}

func (r validator) Struct(s string, mode, typ string) error {
	switch mode {
	case apis2.ModuleDefault:
		var cfg meta.Config
		if err := json.Unmarshal([]byte(s), &cfg); err != nil {
			return err
		}
		return ConfigValidate(r.DB, cfg)
		//switch typ {
		//case apis2.KindApplication:
		//	return ConfigApplicationValidate(r.DB, cfg)
		//case apis2.KindStrategy:
		//	return ConfigStrategyValidate(r.DB, cfg)
		//default:
		//	return fmt.Errorf("unknown type must in %v", apis2.Kinds())
		//}
	case apis2.ModuleHelm:
		return errors.New("we can't create helm config or instance in this version")
	default:
		return errors.New("we can't create helm config or instance in this version")
	}
}

func (r validator) Label(label, configKind, mode, kind string) error {
	switch kind {
	case meta.KindConfig:
		reg, err := configRegexpStrWithOutKind(mode)
		if err != nil {
			return err
		}
		if match, _ := regexp.MatchString(reg, label); !match {
			return fmt.Errorf("can't not macth the label regexp %v", reg)
		}
		return nil
		//reg, err := configRegexpStr(configKind, mode)
		//if err != nil {
		//	return err
		//}
		//if match, _ := regexp.MatchString(reg, label); !match {
		//	return fmt.Errorf("can't not macth the label regexp %v", reg)
		//}
		//return nil
	case meta.KindInstance:
		return nil
	default:
		return errors.New("unknown kind")
	}
}

const invalideNameCharReg = "[_|%]"

func (r validator) Name(name, configKind, mode, kind string) error {
	switch kind {
	case meta.KindConfig:
		if match, _ := regexp.MatchString(invalideNameCharReg, name); match {
			return fmt.Errorf("name contain the char %v", invalideNameCharReg)
		}
		return nil
	case meta.KindInstance:
		if match, _ := regexp.MatchString(invalideNameCharReg, name); match {
			return fmt.Errorf("name contain the char %v", invalideNameCharReg)
		}
		return nil
	default:
		return errors.New("unknown kind")
	}
}
